package com.io.commoncontrol;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.os.Build;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.animation.Animation;
import android.view.animation.CycleInterpolator;
import android.view.animation.TranslateAnimation;

import androidx.appcompat.widget.AppCompatAutoCompleteTextView;

import com.io.commonlib.helper.DensityHelper;
import com.io.commonlib.helper.LogHelper;

/**
 * 自定义edittext样式,带边框的
 * 2020/1/14 9:22
 *
 * @author LiuWeiHao
 * Email 872235631@qq.com
 */
public class EditTextView extends AppCompatAutoCompleteTextView {
    private String mHint;
    private int deleteIconResId;
    private int backgroundResId;
    private Context mContext;
    /**
     * 右侧图片，用于清除输入内容
     */
    private Drawable mClearDrawable;
    private boolean hasFocus;
    private boolean isShowBackground;
    private boolean removable;
    private int borderColor;
    private int cornerRadius;
    private int borderWidth;
    private int custBackgroundColor;


    public EditTextView(Context context) {
        super(context);
        init(context);
    }

    public EditTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.EditTextView);
        deleteIconResId = ta.getResourceId(R.styleable.EditTextView_deleteIconResId, -1);
        backgroundResId = ta.getResourceId(R.styleable.EditTextView_backgroundResId, -1);
        isShowBackground = ta.getBoolean(R.styleable.EditTextView_isBackgroundVisible, true);
        removable = ta.getBoolean(R.styleable.EditTextView_removable, false);
        borderColor = ta.getColor(R.styleable.EditTextView_borderColor, Color.parseColor("#3941ACFF"));
        cornerRadius = ta.getInt(R.styleable.EditTextView_custCornerRadius, 0);
        borderWidth = (int)ta.getDimension(R.styleable.EditTextView_custBorderWidth, DensityHelper.dp2px(context, 1));
        custBackgroundColor = ta.getColor(R.styleable.EditTextView_custBackgroundColor, Color.WHITE);
        init(context);
    }

    public EditTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        mContext = context;
        CharSequence hint = getHint();
        if(hint != null){
            mHint = getHint().toString();
        }
        //获取EditText的DrawableRight,假如没有设置我们就使用默认的图片
        mClearDrawable = getCompoundDrawables()[2];
        if (mClearDrawable == null) {
            if(deleteIconResId != -1){
                mClearDrawable = context.getDrawable(deleteIconResId);
            } else{
                mClearDrawable = context.getDrawable(R.drawable.ic_delete);
            }
        }
        assert mClearDrawable != null;
        mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(), mClearDrawable.getIntrinsicHeight());
        setClearIconVisible(false);
        if(isShowBackground){
            showBackground();
        }
        //this.setPadding(getPaddingLeft(),20,10,22);
    }

    /**
     * 设置边框、背景色
     */
    @SuppressLint("ObsoleteSdkInt")
    public void showBackground() {
        if(backgroundResId == -1){
            GradientDrawable gradientDrawable1 = new GradientDrawable();
            // 形状-圆角矩形
            gradientDrawable1.setShape(GradientDrawable.RECTANGLE);
            gradientDrawable1.setCornerRadius(cornerRadius);
            gradientDrawable1.setStroke(borderWidth, borderColor);
            gradientDrawable1.setColor(custBackgroundColor);
            // 2
            GradientDrawable gradientDrawable2 = new GradientDrawable();
            gradientDrawable2.setShape(GradientDrawable.RECTANGLE);
            gradientDrawable2.setCornerRadius(cornerRadius);
            gradientDrawable2.setColor(custBackgroundColor);
            gradientDrawable2.setStroke(borderWidth, borderColor);
            // 状态选择器
            StateListDrawable stateListDrawable = new StateListDrawable();
            stateListDrawable.addState(new int[]{android.R.attr.state_focused}, gradientDrawable2);
            // 常规状态的背景
            stateListDrawable.addState(new int[]{}, gradientDrawable1);
            // 应用到控件 -- API level 16
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                setBackground(stateListDrawable);
            }
        } else {
            setBackground(mContext.getDrawable(backgroundResId));
        }

    }

    /**
     * 因为我们不能直接给EditText设置点击事件，所以我们用记住我们按下的位置来模拟点击事件
     * 当我们按下的位置 在  EditText的宽度 - 图标到控件右边的间距 - 图标的宽度  和
     * EditText的宽度 - 图标到控件右边的间距之间我们就算点击了图标，竖直方向就没有考虑
     */
    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            if (getCompoundDrawables()[2] != null) {
                boolean touchable = event.getX() > (getWidth() - getTotalPaddingRight())
                        && (event.getX() < ((getWidth() - getPaddingRight())));
                if (touchable) {
                    this.setText("");
                }
            }
        }
        return super.onTouchEvent(event);
    }


    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        this.hasFocus = focused;
        if(removable){
            if (focused) {
                setHint("");
                setClearIconVisible(getText().length() > 0);
            } else {
                setHint(mHint);
                setClearIconVisible(false);
            }
        }
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
    }

    @Override
    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
        if (hasFocus && removable) {
            if (text.length() > 0) {
                setClearIconVisible(true);
            } else {
                setClearIconVisible(false);
            }
        }
        super.onTextChanged(text, start, lengthBefore, lengthAfter);
    }

    /**
     * 设置晃动动画
     */
    public void setShakeAnimation() {
        this.setAnimation(shakeAnimation(5));
    }


    /**
     * 晃动动画
     *
     * @param counts 1秒钟晃动多少下
     * @return 动画
     */
    public static Animation shakeAnimation(int counts) {
        Animation translateAnimation = new TranslateAnimation(0, 10, 0, 0);
        translateAnimation.setInterpolator(new CycleInterpolator(counts));
        translateAnimation.setDuration(1000);
        return translateAnimation;
    }

    /**
     * 默认有光标时选中全部
     */
    @Override
    public void setSelectAllOnFocus(boolean selectAllOnFocus) {
        super.setSelectAllOnFocus(true);
    }


    /**
     * 设置清除图标的显示与隐藏，调用setCompoundDrawables为EditText绘制上去
     *
     * @param visible 是否可见
     */
    protected void setClearIconVisible(boolean visible) {
        Drawable right = visible ? mClearDrawable : null;
        Drawable[] compoundDrawables = getCompoundDrawables();
        setCompoundDrawables(compoundDrawables[0], compoundDrawables[1], right, compoundDrawables[3]);
    }

    /**
     * 设置删除按钮的图片
     * @param id 图片资源id
     */
    protected void setDeleteIconResId(int id){
        if(id != -1){
            deleteIconResId = id;
            mClearDrawable = mContext.getDrawable(deleteIconResId);
        }
    }

    /**
     * 设置输入框的背景
     * @param id 资源id
     */
    protected void seBackgroundResId(int id){
        if(id != -1){
            setBackground(mContext.getDrawable(backgroundResId));
        }
    }
}
